/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * SpringContextUtil<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {
  private static final Map<Class<?>, Object> REGISTER_BEANS = new ConcurrentHashMap<>();

  private static ApplicationContext APPLICATION_CONTEXT;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if (SpringContextUtil.APPLICATION_CONTEXT == null) {
      SpringContextUtil.APPLICATION_CONTEXT = applicationContext;
    }
  }

  public static ApplicationContext getApplicationContext() {
    return APPLICATION_CONTEXT;
  }

  public static Object getBean(String beanName) {
    try {
      return SpringContextUtil.getApplicationContext().getBean(beanName);
    } catch (Exception e) {
      log.error("", e);
      return null;
    }
  }

  public static <T> T getBean(Class<T> clazz) {
    try {
      return SpringContextUtil.getApplicationContext().getBean(clazz);
    } catch (Exception e) {
      log.error("", e);
      return null;
    }
  }

  public static <T> T getBean(String beanName, Class<T> clazz) {
    try {
      return SpringContextUtil.getApplicationContext().getBean(beanName, clazz);
    } catch (BeansException e) {
      log.error("", e);
      return null;
    }
  }

  public static void removeBean(String beanName) {
    DefaultListableBeanFactory defaultListableBeanFactory =
        (DefaultListableBeanFactory) APPLICATION_CONTEXT.getAutowireCapableBeanFactory();
    defaultListableBeanFactory.removeBeanDefinition(beanName);
  }

  @SuppressWarnings("unchecked")
  public static <T> T createBean(Class<T> clazz) {
    AutowireCapableBeanFactory factory = APPLICATION_CONTEXT.getAutowireCapableBeanFactory();
    return (T) factory.createBean(clazz, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
  }

  public static Object registerSingleBean(String className) throws ClassNotFoundException {
    return SpringContextUtil.registerSingleBean(Class.forName(className));
  }

  @SuppressWarnings({"unchecked", "all"})
  public static <T> T registerSingleBean(Class<T> clazz) {
    Object bean = REGISTER_BEANS.get(clazz);
    if (bean == null) {
      synchronized (REGISTER_BEANS) {
        if (bean == null) {
          bean = createBean(clazz);
          REGISTER_BEANS.put(clazz, bean);
        }
      }
    }
    return (T) bean;
  }

  @SuppressWarnings({"unchecked", "null"})
  public static <T> T registerBean(
      String beanName, Class<T> clazz, Map<String, Object> properties, Object... args) {
    try {
      Object bean = SpringContextUtil.getBean(beanName);
      Assert.isFalse(bean == null, "{} wrapper bean, is empty", beanName);
      return (T) bean;
    } catch (Exception e) {
      log.warn(e.getMessage());
      BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
      // 构造函数参数
      if (ArrayUtil.isNotEmpty(args)) {
        for (Object arg : args) {
          builder.addConstructorArgValue(arg);
        }
      }
      // Bean 中字段属性的值设置
      if (CollectionUtil.isNotEmpty(properties)) {
        properties.forEach(builder::addPropertyValue);
      }
      BeanDefinition definition = builder.getRawBeanDefinition();

      BeanDefinitionRegistry registry =
          (BeanDefinitionRegistry) APPLICATION_CONTEXT.getAutowireCapableBeanFactory();
      registry.registerBeanDefinition(beanName, definition);
      return APPLICATION_CONTEXT.getBean(beanName, clazz);
    }
  }
}
